package cn.com.surker.production.service.impl;

import cn.com.surker.common.MessageCenterException;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.production.entity.ProductionOilPrice;
import cn.com.surker.production.dao.ProductionOilPriceDao;
import cn.com.surker.production.service.OilPriceService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.com.surker.spring.RestResultDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import javax.annotation.Resource;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
* <p>
    * 生产运输油价表 服务实现类
    * </p>
*
* @author admin
* @since 2024-12-05
*/
public abstract class ProductionOilPriceBaseServiceImpl extends ServiceImpl<ProductionOilPriceDao, ProductionOilPrice> implements OilPriceService {

    @Resource
    protected ProductionOilPriceDao oilPriceDao;

    /**
     * 查询生产合同油价单价信息
     * @param contractId
     * @return
     */
    public IPage findByContract(Long contractId, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<ProductionOilPrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        if (!StringUtils.isNull(contractId))
            query.eq("contract_id", contractId);
        query.orderByDesc("take_time");

        IPage<ProductionOilPrice> iPage = oilPriceDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 新增生产合同油价单价信息
     * @return
     */
    public RestResultDto savePrice(ProductionOilPrice oilPrice) {
        if (oilPrice == null)
            throw new MessageCenterException("参数错误");
        if (StringUtils.isNull(oilPrice.getOrgId()))
            throw new MessageCenterException("合同公司信息为空");
        if (StringUtils.isNull(oilPrice.getContractId()))
            throw new MessageCenterException("合同信息为空");
        if (StringUtils.isNull(oilPrice.getSupplierId()))
            throw new MessageCenterException("运输商信息为空");
        if (StringUtils.isNull(oilPrice.getToday()))
            throw new MessageCenterException("油价月份为空");
        if (StringUtils.isNull(oilPrice.getTakeTime()))
            throw new MessageCenterException("生效时间为空");
        if (StringUtils.isNull(oilPrice.getCarModel()))
            throw new MessageCenterException("车辆类型为空");
        if (StringUtils.isNull(oilPrice.getAvgPrice()) || oilPrice.getAvgPrice() < 0)
            throw new MessageCenterException("油价月平均价为空或小于0");
        if (StringUtils.isNull(oilPrice.getBasePrice()) || oilPrice.getBasePrice() < 0)
            throw new MessageCenterException("生效时间为空");
        if (StringUtils.isNull(oilPrice.getCalcRate()) || oilPrice.getCalcRate() == 0)
            throw new MessageCenterException("计算系数为空或为0");
        Integer roundType = StringUtils.convertInteger(oilPrice.getRoundType());
        Double adjustPrice = StringUtils.formatDouble((oilPrice.getAvgPrice() - oilPrice.getBasePrice()) / (oilPrice.getCalcRate() / 100), 1, roundType);
        oilPrice.setAdjustPrice(adjustPrice);
        ProductionOilPrice oldOilPrice = oilPriceDao.findTakePrice(oilPrice);
        Date nowDate = new Date();
        if (oldOilPrice != null) {
            oldOilPrice.setUpdateTime(nowDate);
            oldOilPrice.setUpdator(oilPrice.getCreator());
            oldOilPrice.setAdjustPrice(adjustPrice);
            oldOilPrice.setAvgPrice(oldOilPrice.getAvgPrice());
            oldOilPrice.setBasePrice(oilPrice.getBasePrice());
            oldOilPrice.setCalcRate(oilPrice.getCalcRate());
            Integer code = oilPriceDao.updateById(oldOilPrice);
            if (code > 0)
                return RestResultDto.success("保存成功", oldOilPrice);
            return RestResultDto.fail("保存失败");
        }
        oilPrice.setCreateTime(nowDate);
        Integer code = oilPriceDao.insert(oilPrice);
        if (code > 0)
            return RestResultDto.success("保存成功", oilPrice);
        return RestResultDto.fail("保存失败");
    }
    /**
     * 修改油价单价信息
     * @return
     */
    public RestResultDto updatePrice(ProductionOilPrice oilPrice) {
        if (oilPrice == null || StringUtils.isNull(oilPrice.getId()))
            throw new MessageCenterException("参数错误");
        ProductionOilPrice oldOilPrice = oilPriceDao.selectById(oilPrice.getId());
        if (oldOilPrice == null || oldOilPrice.getStatus() == 1)
            throw new MessageCenterException("调整数据不存在或已被删除");
        if (!StringUtils.isNull(oilPrice.getRoundType()) && !StringUtils.isNull(oilPrice.getBasePrice()) && !StringUtils.isNull(oilPrice.getAvgPrice())) {
            Integer roundType = StringUtils.convertInteger(oilPrice.getRoundType());
            Double adjustPrice = StringUtils.formatDouble((oilPrice.getAvgPrice() - oilPrice.getBasePrice()) / (oilPrice.getCalcRate() / 100), 1, roundType);
            oilPrice.setAdjustPrice(adjustPrice);
        }
        oilPrice.setUpdateTime(new Date());
        Integer code = oilPriceDao.updateById(oilPrice);
        if (code > 0)
            return RestResultDto.success("更新成功", oilPrice);
        return RestResultDto.fail("更新失败");
    }

    /**
     * 禁用合同
     * @param id
     * @param status
     * @return
     */
    public RestResultDto updateStatus(Long id, Integer status, String creator) {
        if (StringUtils.isAllParamNull(id, status))
            throw new MessageCenterException("参数错误");
        ProductionOilPrice oldOilPrice = oilPriceDao.selectById(id);
        if (oldOilPrice == null)
            throw new MessageCenterException("调整数据不存在或已被删除");
        oldOilPrice.setUpdateTime(new Date());
        oldOilPrice.setUpdator(creator);
        oldOilPrice.setStatus(status);
        Integer code = oilPriceDao.updateById(oldOilPrice);
        if (code > 0)
            return RestResultDto.success("更新成功", oldOilPrice);
        return RestResultDto.fail("更新失败");
    }

	@Override
	public ProductionOilPrice queryTranPrice(Long tranConId, Integer carModel, String tranTime) {
		if (tranConId == null || StringUtils.isBlank(tranTime)) {
			return null;
		}
		QueryWrapper<ProductionOilPrice> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		if (carModel != null) {
			qw.and(e -> {
				e.eq("car_model", null).or().eq("car_model", carModel);
			});
		}
		qw.eq("contract_id", tranConId);
		qw.le("take_time", tranTime);
		qw.orderByDesc("take_time");
		qw.last("limit 1");
		ProductionOilPrice oilPrice = oilPriceDao.selectOne(qw);
		return oilPrice;
	}
}